package org.spring.springboot.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.spring.springboot.dao.OrderdDao;
import org.spring.springboot.dao.OrdermDao;
import org.spring.springboot.dao.StockDao;
import org.spring.springboot.domain.Orderd;
import org.spring.springboot.domain.Orderm;
import org.spring.springboot.domain.Stock;
import org.spring.springboot.service.OrdermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Service
public class OrdermServiceImpl  extends BaseServiceImpl<Orderm,Integer> implements OrdermService{

    @Autowired
    private OrdermDao ordermDao;
    
    @Autowired
    private StockDao stockDao;
    
    @Autowired
    private OrderdDao orderdDao;

	@Override
	/**
	 * 下订单
	 */
	public synchronized int  order(String ordersjson) {
		
		ArrayList<Orderd> orderdList = new ArrayList<Orderd>();  //订单细节的列表
		ArrayList<Stock> stockList = new ArrayList<Stock>();  //等待更新的库存列表
		Stock stock = null;   //库存
		JSONObject order =null; //订单信息
		Orderd orderd ;  
		Orderm orderm;
		
    	JSONArray orders =new JSONArray();
    	orders=JSONObject.parseArray(ordersjson);
    	
    	//插入订单master表并获取返回的id
    	orderm=new Orderm();
		orderm.setCreateDate(new Date());
		orderm.setSort(1);

		ordermDao.add(orderm);

    	
    	for(int i = 0 ; i<orders.size() ; i++)
    	{
    		order = orders.getJSONObject(i);
    		stock = stockDao.find(order.getIntValue("id"));
    		
    		
    		//检查库存和把商品信息复制到订单子表
//    		if(stock.getNumber()>=order.getIntValue("num"))
//    		{
    			stock.setNumber(stock.getNumber()-order.getIntValue("num"));
    			orderd=new Orderd();
    			orderd.setDescription(stock.getGoods().getDescription());
    			orderd.setGoodsId(stock.getGoodsId());
    			orderd.setName(stock.getGoods().getName());
    			orderd.setImg(stock.getGoods().getImg());
    			orderd.setNum(order.getIntValue("num"));
    			orderd.setPrice(stock.getGoods().getPrice());
    			orderd.setOrdermId(orderm.getId());
    			orderdList.add(orderd);
    			stockList.add(stock);
 //   		}
    	}
    	stockDao.updateBatch(stockList);
    	orderdDao.addBatch(orderdList);
    	return orderm.getId();
    	
	}

	@Override
	public List<Orderm> findByUid(int id) {
		
		return ordermDao.findByUid(id);
	}






}
